/*
 * Copyright 2011 Christoph Ludwig (christoph[at]chludwig.de). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.chludwig.ehumanities.provenance.resources;

import java.net.URI;
import java.util.UUID;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.chludwig.ehumanities.provenance.entities.Archive;
import de.chludwig.ehumanities.provenance.jaxb.ObjectFactory;
import de.chludwig.ehumanities.provenance.jaxb.ZipInfoType;

/**
 * Represents a container that is being zipped.
 */
@Path("/zipping/{containerId}")
public class ZipInProgressResource {

  private static final Logger LOG = LoggerFactory.getLogger(ZipInProgressResource.class);
  
  private Archive archive;

  /**
   * @return the archive
   */
  public Archive getArchive() {
    return archive;
  }

  /**
   * @param archive
   *          the archive to set
   */
  protected void setArchive(Archive archive) {
    this.archive = archive;
  }

  private void setZipInProgress(UUID containerId) {
    setArchive(Archive.archiveWithId(containerId));
  }

  @GET
  @Produces(MediaType.APPLICATION_XML)
  public Response getWorkflowContainerXML(@PathParam("containerId") UUID containerId,
          @Context UriInfo uriInfo) {
    setZipInProgress(containerId);

    ZipInfoType zipInfo = new ZipInfoType();
    Archive archiveEntity = getArchive();
    if (archiveEntity.zipAvailable()) {
      URI zipArchiveUri = uriInfo.getBaseUriBuilder().path(ZipArchiveResource.class).build(containerId.toString());
      zipInfo.setZipArchiveLocator(zipArchiveUri.toASCIIString());
    }
    JAXBElement<ZipInfoType> responseEntity = new ObjectFactory().createZipInfo(zipInfo);
    CacheControl noCache = ProvenanceApplication.noCacheControl();
    LOG.info("GET [{}] status of archive {}", MediaType.APPLICATION_XML, containerId);
    return Response.ok(responseEntity, MediaType.APPLICATION_XML).cacheControl(noCache).build();
  }

}
